<?php

namespace App\Console\Commands;

use App\Library\Lock;
use App\Library\Logic\SalesRecordLogic;
use App\Library\Logic\OrderSplitLogic;
use App\Library\Logic\PaymentLogic;
use App\Library\Logic\PaymentRelatedLogic;
use App\Library\Logic\ShopOrderLogic;
use App\Library\Logic\ShopOrderExtLogic;
use App\Library\Logic\ShopOrderGoodsLogic;
use App\Library\Logic\ShopProductLogic;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ProductOrderSplitCommand extends Command
{
    /**
     * 商品订单拆分
     *
     * @var string
     */
    protected $signature = 'command:productOrderSplit {serialNumber}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command
     * @throws Exception
     */
    public function handle(): void
    {
        $serialNumber = $this->argument('serialNumber');
        if (empty($serialNumber) || strlen($serialNumber) !== 20) return;
        Lock::get($serialNumber . $this->signature, function () use ($serialNumber) {
            $this->handleLock($serialNumber);
        });
    }

    /**
     * handleLock
     * @throws Exception
     */
    private function handleLock(string $serialNumber): void
    {
        $order = ShopOrderLogic::findBySerialNumber($serialNumber);
        if (is_null($order)) return;
        //else if ($order->sell_user_id > 0) return;
        $where = [
            'userId' => $order->buy_user_id,
            'objectType' => $order->getTable(),
            'objectId' => $order->order_id,
        ];
        if (OrderSplitLogic::existsByWhere($where)) return;
        $list = ShopOrderGoodsLogic::query()->where('order_id', $order->order_id)->groupBy('seller_id')->get([
            'seller_id',
            DB::raw('sum(price*quantity) as totalPrice'),
            DB::raw('sum(quantity) as quantity'),
        ]);
        if ($list->count() === 1) {
            $order->sell_user_id = $list[0]->seller_id;
            $order->save();
            $order->ext->status = $order->ext->status_pickup ? 3 : 2;
            $order->ext->save();
            ShopProductLogic::saveSale($order->order_id);
            SalesRecordLogic::shopOrderInvite($order);
            SalesRecordLogic::addOrEditOfShopOrder($order);
            mq('inviteSettlement', $order->serial_number);
            wechatTemplate('newOrder', $order->serial_number);
            return;
        }
        $ids = [];
        foreach ($list as $v) {
            if ($order->discount > 0) {
                $activeDiscount = (float)bcmul($v->totalPrice, bcdiv(100 - $order->discount, 100, 2), 2);
                $v->totalPrice = bcsub($v->totalPrice, $activeDiscount, 2);
            }
            $newOrder = ShopOrderLogic::insertForModel([
                'buyUserId' => $order->buy_user_id,
                'payPrice' => $v->totalPrice,
                'orderTotalPrice' => $v->totalPrice,
                'orderTotalRealPrice' => $v->totalPrice,
                'orderContacts' => $order->order_contacts,
                'orderContactsMobile' => $order->order_contacts_mobile,
                'orderContactsAddress' => $order->order_contacts_address,
                'orderNote' => $order->order_note,
                'sellUserId' => $v->seller_id,
                'orderAddTime' => $order->order_add_time,
                'createdAt' => $order->order_add_time,
                'updatedAt' => time(),
                'orderStatus' => 1,
                'orderBuyStatus' => 1,
                'orderSellStatus' => 1,
                'orderPayTime' => $order->order_pay_time,
                'orderProductNum' => $v->quantity,
                'discount' => $order->discount,
                'activeDiscount' => $activeDiscount ?? 0,
            ]);
            ShopOrderExtLogic::insertForModel([
                'orderId' => $newOrder->order_id,
                'userId' => $newOrder->buy_user_id,
                'sellerId' => $newOrder->sell_user_id,
                'createdAt' => date("Y-m-d H:i:s", $newOrder->order_add_time),
                'status' => 2,
                'statusPay' => 1,
                'payAt' => now(),
            ]);
            ShopOrderGoodsLogic::updateByWhere(['orderId' => $newOrder->order_id], [
                'orderId' => $order->order_id,
                'sellerId' => $v->seller_id,
            ]);
            $ids[] = $newOrder->order_id;
            $paymentRelated = PaymentRelatedLogic::insertForModel([
                'order_sn' => $order->paymentRelated->serial_number,
                'objectType' => $order->getTable(),
                'objectId' => $newOrder->order_id,
                'statusPay' => 1,
                'config' => $order->paymentRelated->config,
            ]);
            $order->payment->payment_related_id = $paymentRelated->id;
            $order->payment->object_id = $paymentRelated->object_id;
            unset($order->payment->serial_number);
            PaymentLogic::insertForModel($order->payment->toArray());
            SalesRecordLogic::shopOrderInvite($newOrder);
            SalesRecordLogic::addOrEditOfShopOrder($newOrder);
            ShopProductLogic::saveSale($newOrder->order_id);
            mq('inviteSettlement', $newOrder->serial_number);
            wechatTemplate('newOrder', $newOrder->serial_number);
        }
        $order->buy_user_id = 0;
        $order->save();
        OrderSplitLogic::insertForModel(array_merge($where, [
            'newIds' => $ids,
            'info' => $order->goodShot,
        ]));
    }
}
